<?php

namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Sku as SkuService;

class AutoAssign extends Admin
{

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 返单列表
     *
     * @author King
     * @date 2020年8月11日
     *
     * @return string
     */
    public function backOrder()
    {
        $action=$this->request->param('action', '');
        if ($this->request->isAjax()) {
        	$skuService = new SkuService();
        	$factoryKV = getFactoryKV(true);

        	$hadOutgoOrderIdArr = []; // 外发过的订单
        	$hadnotOutgoOrderIdArr = []; // 未外发过的订单
        	$where = [
        		['status', 'in', [0, 1]],
        		['o.factory_id', '=', 0],
        		['is_new', '=', 1],
        	];
            $complexityArr=['简','<font color="green">易</font>','<font color="orange">难</font>'];
        	$list = db('order o')->join('sku sku', 'o.sku = sku.sku','left')
                ->field("quantity,client_ordernum,shipment_time,o.id,o.factory_id,sku.cost_little,sku.cost,
                o.sku,o.is_auto_import,o.type,o.o_type,sku.fabrics_process_complexity,sku.pic,sku.sku_type")->order('is_auto_import asc,fabrics_process_complexity desc')->where($where)->select();
            $knitOrders=$tatOrders=$knitComplexityOrders=$tatComplexityOrders=[];
            foreach ($list as $k => $v) {
                $v['fabrics_process_complexity']=$v['fabrics_process_complexity']==''? 1: $v['fabrics_process_complexity'];
                $v['complexity_str']=$complexityArr[$v['fabrics_process_complexity']];
                if($v['sku_type']=='针织'){
                    $knitOrders[$v['is_auto_import']][$v['fabrics_process_complexity']][]=$v;  //0否，1小辉辉，2名贵坊，3十义
                    //$knitComplexityOrders[$v['fabrics_process_complexity']][]=$v;
                }else{ //梭织
                    $tatOrders[$v['is_auto_import']][$v['fabrics_process_complexity']][]=$v;//面辅工艺难度 0简1易2难
                    //$tatComplexityOrders[$v['fabrics_process_complexity']][]=$v;
                }
            }
            $retstr= "//面辅工艺难度 0简1易2难";
            foreach($knitOrders as $accountId=>$orders) { //所有帐号下的针织订单 进行分配
                $retstr.="帐号$accountId 针织:";
                foreach ($orders as $complexityId => $smOrderlist) {
                    $retstr.= "难度".$complexityId."， 订单个数：".count($smOrderlist)."个";
                }
            }
            foreach($tatOrders as $accountId=>$orders) { //所有帐号下的针织订单 进行分配
                $retstr.="帐号$accountId 梭织:";
                foreach ($orders as $complexityId => $smOrderlist) {
                    $retstr.= "难度".$complexityId."， 订单个数：".count($smOrderlist)."个";
                }
            }
            $newList=[];//已设置工厂的订单
            // 需分配的工厂
            $factoryList = db('factory_setting')
                ->where("status", 1)->field('*')->order('id asc')->select();
            $accountKeyVal=['','knit_one_per','knit_two_per','knit_thr_per'];
            $perName=['knit_one_per'=>'小辉辉针织','knit_two_per'=>'名贵坊针织','knit_thr_per'=>'十义针织','tat_one_per'=>'小辉辉梭织','tat_two_per'=>'名贵坊梭织','tat_thr_per'=>'十义梭织'];
            $giveRetstr='';
            $complexityArr=['简单','容易','困难'];
            $chartData=[];
            foreach ($factoryList as $v) {
                $giveRetstr.="<div></div><b>".$factoryKV[$v['factory_id']]."</b>-->";
                if($v['knit_one_per']>0 || $v['knit_two_per']>0 || $v['knit_thr_per']>0){ //针织有百分比 进行分配
                    foreach($knitOrders as $accountId=>&$orders){ //所有帐号下的针织订单 进行分配  $accountId 1,2
                        foreach ($orders as $complexityId=>&$smOrderlist){ //循环帐号下所有难度列表订单
                            $canHaveCount=floor($v[$accountKeyVal[$accountId]]/100 * count($smOrderlist)); //按难易比例分配,计算分配个数  $v[$accountKeyVal[$accountId]]各帐号的分配比例
                            if($v[$accountKeyVal[$accountId]]>0)
                            $giveRetstr.=$perName[$accountKeyVal[$accountId]].'比例'.$v[$accountKeyVal[$accountId]]."%，难度:".$complexityArr[$complexityId]."， 订单个数：".count($smOrderlist)."个，分配个数".$canHaveCount."；<br>";
                            $chartData[$v['factory_id']][$complexityId]=isset($chartData[$v['factory_id']][$complexityId]) ? $chartData[$v['factory_id']][$complexityId] :0;
                            $chartData[$v['factory_id']][$complexityId]+=$canHaveCount;
                            if($canHaveCount>0){
                                foreach ($smOrderlist as $key=>&$orderinfo){
                                    if($orderinfo['factory_id']<=0){
                                        $orderinfo['factory_id']=$v['factory_id'];
                                        $canHaveCount-=1;
                                    }
                                    if($canHaveCount<=0){
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                $tatKeyVal=['','tat_one_per','tat_two_per','tat_thr_per'];
                if($v['tat_one_per']>0 || $v['tat_two_per']>0 || $v['tat_thr_per']>0){ //针织有百分比 进行分配
                    foreach($tatOrders as $accountId=>&$orders){ //所有帐号下的针织订单 进行分配  $accountId 1,2
                        foreach ($orders as $complexityId=>&$smOrderlist){ //循环帐号下所有难度列表订单
                            $canHaveCount=floor($v[$tatKeyVal[$accountId]]/100 * count($smOrderlist)); //按难易比例分配,计算分配个数  $v[$accountKeyVal[$accountId]]各帐号的分配比例
                            if($v[$tatKeyVal[$accountId]]>0)
                            $giveRetstr.=$perName[$tatKeyVal[$accountId]].'比例'.$v[$tatKeyVal[$accountId]]."%，难度:".$complexityArr[$complexityId]."， 订单个数：".count($smOrderlist)."个，分配个数".$canHaveCount."；<br>";
                            $chartData[$v['factory_id']][$complexityId]=isset($chartData[$v['factory_id']][$complexityId]) ? $chartData[$v['factory_id']][$complexityId] :0;
                            $chartData[$v['factory_id']][$complexityId]+=$canHaveCount;
                            if($canHaveCount>0){
                                foreach ($smOrderlist as $key=>&$orderinfo){
                                    if($orderinfo['factory_id']<=0){
                                        $orderinfo['factory_id']=$v['factory_id'];
                                        $canHaveCount-=1;
                                    }
                                    if($canHaveCount<=0){
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                $giveRetstr.="</div>";
            }
            $historyAssigns=db("order")->field("count(id) as order_count,FROM_UNIXTIME(assign_factory_date,'%Y-%m-%d') as setday,sum(quantity) as tot_quantity,factory_id")
                ->where('factory_id','>',0)
                ->where('assign_factory_date','egt',strtotime(date('Y-m-d',strtotime("-15 days"))))->group("factory_id,FROM_UNIXTIME(assign_factory_date,'%Y-%m-%d')")
                ->order('assign_factory_date desc')->select();
            $backOrders=db("order")->field("count(id) as order_count,FROM_UNIXTIME(create_time,'%Y-%m-%d') as setday,sum(quantity) as tot_quantity,factory_id")
                ->where('create_time','egt',strtotime(date('Y-m-d',strtotime("-15 days"))))
                ->where([['status', 'in', [0, 1]],['is_new', '=', 0]])->group("factory_id,FROM_UNIXTIME(create_time,'%Y-%m-%d')")
                ->order('create_time desc')->select();
            $historyBackOrders=[];
            foreach ($backOrders as $index=>$info){
                $historyBackOrderCounts[$info['factory_id']][$info['setday']]=$info['order_count'];
                $historyBackOrderQuantitys[$info['factory_id']][$info['setday']]=$info['tot_quantity'];
            }

            $dateArr=array_unique(array_column($historyAssigns,'setday'));
            sort($dateArr);
            $factoryidArr=array_unique(array_column($historyAssigns,'factory_id'));
            $formatHistoryAssigns=$orderQuantityAssigns=[];
            foreach ($historyAssigns as $index=>$info){
                $formatHistoryAssigns[$info['factory_id']][$info['setday']]=$info['order_count'];
                $orderQuantityAssigns[$info['factory_id']][$info['setday']]=$info['tot_quantity'];
            }
            $factoryChartList=[];
            foreach ($factoryidArr as $key=>$factoryid){
                $backOrderSimp=[];
                $backOrderSimp['name']=$factoryKV[$factoryid].'返单';
                foreach ($dateArr as $i=>$setday){
                    $backOrderSimp['data'][]=isset($historyBackOrderCounts[$factoryid][$setday]) ? $historyBackOrderCounts[$factoryid][$setday] : 0;
                    $backOrderSimp['stack']='f'.$factoryid;
                }
                $factoryChartList[]=$backOrderSimp;
                $factorySimp=[];
                $factorySimp['name']=$factoryKV[$factoryid];
                foreach ($dateArr as $i=>$setday){
                    $factorySimp['quantity']=isset($orderQuantityAssigns[$factoryid][$setday]) ? $orderQuantityAssigns[$factoryid][$setday] : 0;
                    $factorySimp['data'][]=isset($formatHistoryAssigns[$factoryid][$setday]) ? $formatHistoryAssigns[$factoryid][$setday] : 0;
                    $factorySimp['stack']='f'.$factoryid;
                }
                $factoryChartList[]=$factorySimp;
            }
            //返单数据

            $historyAssign['list']=$factoryChartList;
            $historyAssign['date']=$dateArr;
            $chartCompArr=$factoryNameArr=[];
            if(count($list)<=0){ //造空模板图形数据
                foreach ($factoryList as $v) {
                    foreach ([0,1,2] as $key=>$complexityId){
                        $chartData[$v['factory_id']][$complexityId] = 0;
                    }
                }
            }
            foreach ($chartData as $factoryid=>$compidarr){
                $chartCompArr[0][]=isset($compidarr[0]) ? $compidarr[0] : 0;
                $chartCompArr[1][]=isset($compidarr[1]) ? $compidarr[1] :0;
                $chartCompArr[2][]=isset($compidarr[2]) ? $compidarr[2] : 0;
                $factoryNameArr[]=$factoryKV[$factoryid];
            }
            asort($knitOrders);
            asort($tatOrders);
            //print_r($knitOrders);
            $peopleAssignOrders=[];
            $allOrders=[$knitOrders];//$tatOrders
            foreach ($knitOrders as $accountId => $complexityOrders) {
                foreach ($complexityOrders as $complexityId=>$smlist){
                    foreach ($smlist as $info){
                        $info['tags'] = getOrderTag($info);
                        if ($info['factory_id'] <= 0) {
                            $peopleAssignOrders[] = $info;
                        } else {
                            $newList[] = $info;
                        }
                    }
                }
            }
            foreach ($tatOrders as $accountId => $complexityOrders) {
                foreach ($complexityOrders as $complexityId=>$smlist){
                    foreach ($smlist as $info){
                        $info['tags'] = getOrderTag($info);
                        if ($info['factory_id'] <= 0) {
                            $peopleAssignOrders[] = $info;
                        } else {
                            $newList[] = $info;
                        }
                    }
                }
            }


            $retstr=$giveRetstr;
        	return $this->Json(1, '', ['list' => $list,'retstr'=>$retstr,'chartCompArr'=>$chartCompArr,'factoryNameArr'=>$factoryNameArr,'today'=>date('Y-m-d'),
        		'historyAssign'=>$historyAssign,
        		'setlist'=>$newList,'peopleAssign'=>$peopleAssignOrders,
        		'factoryKV' => ['0' => '请选择']+$factoryKV,
        		'order_count' => count($newList) ,
        		'people_assign_count'=>count($peopleAssignOrders),
        		'quantity' => array_sum(array_column($newList, 'quantity')),
        		'people_quantity'=>array_sum(array_column($peopleAssignOrders, 'quantity')),
                ]);
        }
        $template=$action=='showCharts'?'assigncharts' : '';
        $assign = [];
        return $this->assign($assign)->fetch($template);
    }

    private function _todayFactoryAssigns(){

    }

    /**
     * 返单分配
     *
     * @author King
     * @date 2020年8月11日
     *
     */
    public function backOrderAssign() {
    	$factoryIds = $this->request->param('factory_id/a', []);
    	$outgoIds = $this->request->post('is_outgo/a', []);
        $factoryKV = getFactoryKV(true);
    	foreach ($factoryIds as $orderId => $factoryId) {
    	    if($factoryId==0) continue;
    		$orderData = [
    			'factory_id' => $factoryId,
    			'assign_factory_date' => time(),
    		];
    		//if($factoryId==0) continue;
    		db('order')->where('id', $orderId)->update($orderData);
    		$this->addOrderLog($orderId, '', "批量自动分配工厂 到 " . $factoryKV[$factoryId]);
    	}
    	return $this->Json(1, '分配成功');
    }

    /**
     * 工厂接单分配比例设置
     *
     * @author King
     * @date 2020年8月11日
     *
     * @return string
     */
    public function setting() {
		if ($this->request->isAjax()) {
			$probabilityArr = $this->request->param('probability/a', []);
			$probabilityOutgoArr = $this->request->param('probability_outgo/a', []);
			$statusArr = $this->request->param('status/a', []);
            $account_one_per=$this->request->param('knit_one_per/a', []);
            $account_two_per=$this->request->param('knit_two_per/a', []);
            $account_thr_per=$this->request->param('knit_thr_per/a', []);
            $tat_one_per=$this->request->param('tat_one_per/a', []);
            $tat_two_per=$this->request->param('tat_two_per/a', []);
            $tat_thr_per=$this->request->param('tat_thr_per/a', []);
            $fabric_process_addr=$this->request->param('fabric_process_addr/a', []);
            if(array_sum($account_one_per)>100 || array_sum($account_two_per)>100 || array_sum($account_thr_per)>100 || array_sum($tat_one_per)>100 || array_sum($tat_two_per)>100 || array_sum($tat_thr_per)>100){
                return $this->Json('err','各项分配百分比均不能超过100%,请检查分配比例');
            }
			foreach ($account_one_per as $factoryId => $v) {
				$info = db('factory_setting')->where("factory_id", $factoryId)->find();
				$upData = [
					'factory_id' => $factoryId,
					//'probability' => round($v, 2),
					//'probability_outgo' => round($probabilityOutgoArr[$factoryId], 2),
                    'knit_one_per' => round($account_one_per[$factoryId], 2),
                    'knit_two_per' => round($account_two_per[$factoryId], 2),
                    'knit_thr_per' => round($account_thr_per[$factoryId], 2),
                    'tat_one_per' => round($tat_one_per[$factoryId], 2),
                    'tat_two_per' => round($tat_two_per[$factoryId], 2),
                    'tat_thr_per' => round($tat_thr_per[$factoryId], 2),
                    'fabric_process_addr' => arrayGet($fabric_process_addr, $factoryId, 0),
                    'status' => arrayGet($statusArr, $factoryId, 0)?1:0,
					'update_time' => time(),
				];
				if ($info) {
					db('factory_setting')->where("id", $info['id'])->update($upData);
				} else {
					$upData['create_time'] = time();
					db('factory_setting')->insertGetId($upData);
				}
			}
			return $this->Json(1);
		}
    	$list = db('factory_setting')->order('id asc')->column('*', 'factory_id');
		foreach ($list as $key=>&$item){
            $item['knit_one_per']=$item['knit_one_per']<=0 ? "" : $item['knit_one_per'];
            $item['knit_two_per']=$item['knit_two_per']<=0 ? "" : $item['knit_two_per'];
            $item['knit_thr_per']=$item['knit_thr_per']<=0 ? "" : $item['knit_thr_per'];
            $item['tat_one_per']=$item['tat_one_per']<=0 ? "" : $item['tat_one_per'];
            $item['tat_two_per']=$item['tat_two_per']<=0 ? "" : $item['tat_two_per'];
            $item['tat_thr_per']=$item['tat_thr_per']<=0 ? "" : $item['tat_thr_per'];
        }
    	$assign = [
    		'list' => $list,
    		'factoryKV' => getFactoryKV(true),
    	];
    	return $this->assign($assign)->fetch();
    }

}